import {
  getLegendsType,
  createLegendsType,
  deleteLegendsType,
} from "../service/legends.service.js";
// 查询所有分类
export const getTypeList = async (ctx, next) => {
  try {
    const res = await getLegendsType();
    ctx.body = {
      code: 200,
      message: "获取分类成功",
      data: res,
    };
  } catch (error) {
    ctx.app.emit("error", {
      code: 10001,
      message: "获取分类失败",
      result: "",
    });
  }

  await next();
};

// 新建分类
export const createType = async (ctx, next) => {
  const { typeName } = ctx.request.body;

  const res = await createLegendsType(typeName);

  if (res) {
    ctx.body = {
      code: 200,
      message: "创建分类成功",
      data: res,
    };
  } else {
    return ctx.app.emit(
      "error",
      {
        code: 10001,
        message: "创建分类失败,分类已存在",
        result: null,
      },
      ctx
    );
  }

  await next();
};
// 删除分类
export const deleteType = async (ctx, next) => {
  const id = ctx.params.id;
  try {
    const res = await deleteLegendsType(id);
    console.log(res);
    if (res) {
      ctx.body = {
        code: 200,
        message: "删除成功",
        result: res,
      };
    } else {
      return ctx.app.emit(
        "error",
        {
          code: 10001,
          message: "删除失败",
          result: "",
        },
        ctx
      );
    }
  } catch (error) {
    return ctx.app.emit("error", {
      code: 10001,
      message: "删除失败",
      result: "",
    });
  }
};
